package ewa

import (
	"net/http"
  "fmt"
	"github.com/labstack/echo"
)

const (
  NotifyWrongCookie = "You don’t have permission to access this page!\n"+
      "Please login on the Portal page first,\n"+
      "Then you will get the access token.\n"

  NotifyWrongToken =  "You don’t have permission to access this api!\n"+
      "Please login on the Portal api first,\n"+
      "Then you will get the access token.\n"
)

//type RestrictRouteCb func(echo.Context) error

/* Restrict Route GET, 
   需要cookies, 
   需要token验证  */
func CbCookieTokenGet(c echo.Context) error {
  //fmt.Printf("Path: %s\n", c.Path())	//such like as '/test.html'
  utype, uri := HttpReqPathSuffix(c.Path())

  if utype == URITYPE_RES {
    //cookie 解析出token   
    token, err := c.Cookie("token")
    if err != nil {
      l:=fmt.Sprintf("----Echo/> browser cookie wrong!");Log(l)
      return c.String(http.StatusOK, NotifyWrongCookie)
    }
    l:=fmt.Sprintf("----Echo/> Fetch client local storage(browser cookie) key:%s  value:%s", token.Name, token.Value)
    Log(l)
    //token decode 解码
    claims, token_err := JwtTokenDecode(token.Value)
    l=fmt.Sprintf("----Echo/> JWT token.user:%s, token.error:%v", claims.Name, token_err); Log(l)
    
    if token_err != nil{
      l=fmt.Sprintf("----Echo/> JWT token wrong!");Log(l)
      return c.String(http.StatusOK, NotifyWrongCookie)
    }else {
      //指定网页模板名称: uri
      l:=fmt.Sprintf("----Echo/> Response render page[%s]", uri)
      Log(l)
      return c.Render(http.StatusOK, uri, "")
    }
  }else if utype == URITYPE_API {
      // 
      if CfgRoute.MApiAttr[uri].SyncAck == true {
        return SyncApiResponse(uri, c)
      }else{
        return AsyncApiResponse(uri, c)
      }
  }
  return nil
}

func RouteRegistry_CookieTokenGet(route string, e *echo.Echo, cb RestrictRouteCb) {
  l:=fmt.Sprintf("----Echo/> regist CookieTokenGet '%s'", route);Log(l)
	e.GET(route, (echo.HandlerFunc)(cb))
}